<?php
/**
 * Created by PhpStorm.
 * User: hetu
 * Date: 2018/5/7
 * Time: 9:51
 */

namespace backend\controllers;

use backend\models\form\EvaluForm;
use backend\service\EvaluService;
use common\models\Evalu;
use common\service\BaseToolService;
use Yii;
use backend\service\RbacService;
use backend\models\form\RoleForm;
use yii\helpers\Url;
use backend\service\ColumnService;
use backend\models\form\RolePermissionForm;
use backend\models\form\AdminUserForm;
use backend\service\AdminUserService;
use yii\helpers\ArrayHelper;
use backend\models\AdminUser;
use backend\models\form\RegisterForm;
use common\models\ContralSet;
use yii\data\Pagination ;
use backend\models\form\ContralSetForm;
use common\service\MessageService;
use backend\models\GoogleAuthenticator;
use backend\service\GoogleAuthenticatorService;
use yii\web\Response;
use common\service\UtilService;
use yii\web\UploadedFile;

class SystemController extends BaseController
{
    /**
     * 角色列表
     */
    public function actionRoleList ()
    {
        $role_name = Yii::$app->request->get('role_name');

        if (strlen($role_name) > 24) {
            return $this->redirect(["tip/index", "msg" => "搜索角色名称不可超过8字", "url" => Url::toRoute(["/system/role-list"])]);
        }

        $roles = RbacService::findRolesByName($role_name);

        return $this->render("role_list", ["roles" => $roles['list'], "pages" => $roles['pages']]);
    }

    /**
     * 添加角色
     */
    public function actionAddRole () {
        $model = new RoleForm();
        $post_data = Yii::$app->request->post();
        if ($model->load($post_data) && $model->validate()) {
            $add_rs = $model->addRole();
        } else if (Yii::$app->request->isPost) {
            return $this->returnAjax(400, current($model->getFirstErrors()), Url::toRoute("'role-list'"));
        }
        if (!empty($add_rs) && $add_rs['status'] == false) {
            return $this->returnAjax(400, $add_rs['msg'], Url::toRoute('role-list'));
        }

        $role_name = $model->name;

        $permissionsmodel = new RolePermissionForm();
        //角色当前所拥有权限
        $edit_re = RbacService::findPermissionsByRole($role_name);
        $my_permis = array();
        foreach ($edit_re as $key => $value) {
            $my_permis[] = $value->name;
        }
        //全部模块栏目
        $column_arr = ColumnService::findColumnList(null, 1, 0);
        //全部权限
        $permissions = RbacService::findPermissions();
        $edit_all = array();
        foreach ($permissions as $key => $value) {
            $edit_all[$key]['name'] = $value->name;
            $edit_all[$key]['description'] = $value->description;
            $edit_all[$key]['createdAt'] = $value->createdAt;
            //拆分权限name用于跟模块tag对应
            $ex_column = explode('/', $value->name);
            $edit_all[$key]['column_name'] = $ex_column[0];
        }
        //不改变查询结构，对所有权限重新进行排序，按添加时间
        foreach ($edit_all AS $uniqid => $row) {
            foreach ($row AS $key => $value) {
                $arrSort[$key][$uniqid] = $value;
            }
        }
        array_multisort($arrSort['createdAt'], SORT_ASC, $edit_all);
        //对模块栏目数据进行遍历
        $column_all = array();
        $column_alls = array();
        foreach ($column_arr['list'] as $key => $value) {
            $column_all[$key]['tag'] = $value['tag'];
            $column_all[$key]['tag_name'] = $value['name'];
            //把存在的模块集合用于判断不属于模块的权限问题
            $column_alls[] = $value['tag'];
        }
        $post_data = Yii::$app->request->post();
        if (YIi::$app->request->isPost) {
            if (!isset($post_data['RolePermissionForm']['permission'])) {
                $post_data['RolePermissionForm']['permission'][] = '';
                $post_datas = $post_data['RolePermissionForm']['permission'];
                //根据角色所拥有的权限对比传值需要修改的权限,取差值,删除权限
                $diff_data = array_diff($my_permis, $post_datas);

                if ($diff_data) {
                    RbacService::delRolePermissions($role_name, $diff_data);
                }
                return $this->returnAjax(200, '角色添加成功', Url::toRoute('role-list'));
            } else {
                if ($permissionsmodel->load($post_data, 'RolePermissionForm') && $permissionsmodel->validate()) {
                    $post_datas = $post_data['RolePermissionForm']['permission'];
                    //根据角色所拥有的权限对比传值需要修改的权限,取差值,删除权限
                    $diff_data = array_diff($my_permis, $post_datas);
                    //根据传值需要修改的权限对比角色所拥有的权限,取差值,增加权限
                    $diff_post = array_diff($post_datas, $my_permis);

                    if ($diff_data) {
                        RbacService::delRolePermissions($role_name, $diff_data);
                    }
                    if ($diff_post) {
                        RbacService::addRolePermissions($role_name, $diff_post);
                    }
                    return $this->returnAjax(200, '角色添加成功', Url::toRoute('role-list'));
                }
            }
        }
        return $this->renderPartial("add_role", ["model" => $model, "permissionsmodel" => $permissionsmodel, "edit_res" => $my_permis, "edit_all" => $edit_all, 'column_all' => $column_all, 'column_alls' => $column_alls]);
    }


    /**
     * 删除角色
     */
    public function actionDelRole() {
        $role_name_post = Yii::$app->request->post("role_name");

        $getdata = Yii::$app->request->get();

        if (empty($role_name_post)) {
            return $this->returnAjax(400, '请不要乱操作', Url::toRoute('role-list'));
        }

        $userrole = RbacService::findUserByRole($role_name_post);

        if ($userrole) {
            return $this->returnAjax(400, '该角色存在应用用户，不可删除', Url::toRoute('role-list'));
        }

        $del_rs = RbacService::delRole($role_name_post);
        array_unshift($getdata, 'role-list');
        return $this->returnAjax(200, $del_rs['msg'], Url::toRoute($getdata));
    }

    /**
     * 更新角色
     */
    public function actionUpdRole() {
        $role_name = Yii::$app->request->get("role_name");
        $getdata = Yii::$app->request->get();
        unset($getdata['role_name']);
        if (!empty($getdata['rolename'])) {
            $getdata['role_name'] = $getdata['rolename'];
            unset($getdata['rolename']);
        } else {
            unset($getdata['rolename']);
        }
        if (empty($role_name)) {
            return $this->returnAjax(400, '请不要乱操作', Url::toRoute('role-list'));
        }

        $model = new RoleForm();
        $post_data = Yii::$app->request->post();
        if ($model->load($post_data, 'RoleForm') && $model->validate()) {
            $upd_rs = $model->updRole();
        } else if (Yii::$app->request->isPost) {
            return $this->returnAjax(400, current($model->getFirstErrors()), Url::toRoute("'role-list'"));
        }

        if (empty($upd_rs)) {
            $role = RbacService::findRoleByName($role_name);
            $model->name = $role->name;
            $model->desc = $role->description;
        } elseif ($upd_rs['status'] == false) {
            return $this->returnAjax(400, $upd_rs['msg'], Url::toRoute('role-list'));
        }
        $role_name = $model->name;
        $permissionsmodel = new RolePermissionForm();
        //角色当前所拥有权限
        $edit_re = RbacService::findPermissionsByRole($role_name);
        $my_permis = array();
        foreach ($edit_re as $key => $value) {
            $my_permis[] = $value->name;
        }
        //全部模块栏目
        $column_arr = ColumnService::findColumnList(null, 1, 0);
        //全部权限
        $permissions = RbacService::findPermissions();
        $edit_all = array();
        foreach ($permissions as $key => $value) {
            $edit_all[$key]['name'] = $value->name;
            $edit_all[$key]['description'] = $value->description;
            $edit_all[$key]['createdAt'] = $value->createdAt;
            //拆分权限name用于跟模块tag对应
            $ex_column = explode('/', $value->name);
            $edit_all[$key]['column_name'] = $ex_column[0];
        }
        //不改变查询结构，对所有权限重新进行排序，按添加时间
        foreach ($edit_all AS $uniqid => $row) {
            foreach ($row AS $key => $value) {
                $arrSort[$key][$uniqid] = $value;
            }
        }
        array_multisort($arrSort['createdAt'], SORT_ASC, $edit_all);
        //对模块栏目数据进行遍历
        $column_all = array();
        $column_alls = array();
        foreach ($column_arr['list'] as $key => $value) {
            $column_all[$key]['tag'] = $value['tag'];
            $column_all[$key]['tag_name'] = $value['name'];
            //把存在的模块集合用于判断不属于模块的权限问题
            $column_alls[] = $value['tag'];
        }
        $post_data = Yii::$app->request->post();
        if (YIi::$app->request->isPost) {
            if (!isset($post_data['RolePermissionForm']['permission'])) {
                $post_data['RolePermissionForm']['permission'][] = '';
                $post_datas = $post_data['RolePermissionForm']['permission'];
                //根据角色所拥有的权限对比传值需要修改的权限,取差值,删除权限
                $diff_data = array_diff($my_permis, $post_datas);

                if ($diff_data) {
                    RbacService::delRolePermissions($role_name, $diff_data);
                }
                array_unshift($getdata, 'role-list');
                return $this->returnAjax(200, '角色修改成功', Url::toRoute($getdata));
            } else {
                if ($permissionsmodel->load($post_data, 'RolePermissionForm') && $permissionsmodel->validate()) {
                    $post_datas = $post_data['RolePermissionForm']['permission'];
                    //根据角色所拥有的权限对比传值需要修改的权限,取差值,删除权限
                    $diff_data = array_diff($my_permis, $post_datas);
                    //根据传值需要修改的权限对比角色所拥有的权限,取差值,增加权限
                    $diff_post = array_diff($post_datas, $my_permis);

                    if ($diff_data) {
                        RbacService::delRolePermissions($role_name, $diff_data);
                    }
                    if ($diff_post) {
                        RbacService::addRolePermissions($role_name, $diff_post);
                    }
                    array_unshift($getdata, 'role-list');
                    return $this->returnAjax(200, '角色修改成功', Url::toRoute($getdata));
                }
            }
        }
        return $this->renderPartial("upd_role", ["model" => $model, "permissionsmodel" => $permissionsmodel, "edit_res" => $my_permis, "edit_all" => $edit_all, 'column_all' => $column_all, 'column_alls' => $column_alls, 'role_name' => $role_name]);
    }

    /**
     * 后台用户管理
     */
    public function actionAdminUser() {
        $model = new AdminUserForm();
        $model->load(\Yii::$app->request->get(),'');
        if (!$model->validate()){
            return $this->redirect([
                "tip/index",
                "msg"=>current($model->getFirstErrors()),
                "url"=>Url::toRoute([$this->id."/admin-user"])
            ]);
        }
        $results = AdminUserService::getAdminUserList($model);

        $create_user_ids = ArrayHelper::getColumn($results['list'],'create_user_id');
        $adminUserInfo = AdminUser::findAll($create_user_ids);
        $adminUserInfo = ArrayHelper::index($adminUserInfo,'user_id');
        foreach($results['list'] as &$value){
            if(!empty($adminUserInfo[$value['create_user_id']]['username'])){
                $username = $adminUserInfo[$value['create_user_id']]['username'];
            }else{
                $username = "";
            }
            $value['create_user_id'] = $username;
        }

        return $this->render('admin_user',['model'=>$results['model'],'list'=>$results['list'],'pages'=>$results['pages'],'role'=>$results['role']]);
    }

    /**
     * 后台用户重置密码
     */
    public function actionResetPasswords() {
        $model = new AdminUserForm();
        $getdata = Yii::$app->request->get();
        unset($getdata['user_id']);
        array_unshift($getdata, "/system/admin-user");
        $model->load(\Yii::$app->request->get(),'');

        $user = AdminUser::find()->where(['user_id' => $model->user_id])->one();

        if ($user->username == 'admin') {
            return $this->redirect([
                "tip/index",
                "msg"=>"不能重置超级管理员",
                "url"=>Url::toRoute($getdata)
            ]);
        }

        if (!$model->validate()){
            return $this->redirect([
                "tip/index",
                "msg"=>current($model->getFirstErrors()),
                "url"=>Url::toRoute($getdata)
            ]);
        }
        $results = AdminUserService::resetPasswords($model);
        return $this->redirect([
            "tip/index",
            "msg"=>$results['msg'],
            "url"=>Url::toRoute($getdata)
        ]);
    }

    /**
     * 添加用户
     */
    public function actionAddUser(){
        $model = new RegisterForm() ;
        $model->setScenario("add");
        $post_data = Yii::$app->request->post() ;

        if(!YIi::$app->request->isPost){
            return $this->renderPartial('add_user',["model"=>$model]);
        }

        if(empty($post_data['RegisterForm']['username'])){
            return $this->returnAjax(400, "姓名不能为空", Url::toRoute("/system/admin-user"));
        }
        if(empty($post_data['RegisterForm']['phone'])){
            return $this->returnAjax(400, "手机不能为空", Url::toRoute("/system/admin-user"));
        }

        $model->username = $post_data['RegisterForm']['username'];
        $model->phone = $post_data['RegisterForm']['phone'] ;
        $model->status = $post_data['RegisterForm']['status'];
        $model->role = $post_data['RegisterForm']['role'];
        $model->password =$post_data['RegisterForm']['password'];
        $model->avatar  = UploadedFile::getInstance($model, 'avatar');

        if(!$model->validate()){
            return $this->returnAjax(400, current($model->getFirstErrors()), Url::toRoute("/system/admin-user"));
        }
        $add_rs = $model->addUser() ;
        return $this->returnAjax(200, $add_rs['msg'], Url::toRoute("/system/admin-user"));
    }

    /**
     * 修改用户
     */
    public function actionEditUser(){
        $model = new RegisterForm() ;
        $use_id = Yii::$app->request->get("user_id");

        $getdata = Yii::$app->request->get();
        unset($getdata['user_id']);

        $user = AdminUser::findOne(["user_id"=>$use_id]);
        if(empty($user)){
            return $this->returnAjax(400, "无此工号", Url::toRoute("/system/admin-user"));
        }

        if(YIi::$app->request->isPost){

            if ($user['username'] == 'admin' && Yii::$app->admin->identity->username != 'admin') {
                return $this->returnAjax(400, "非超级管理员无法修改超级管理员", Url::toRoute("/system/admin-user"));
            }

            $post_data = Yii::$app->request->post() ;
            $model->username = $post_data['RegisterForm']['username'];
            $model->phone = $post_data['RegisterForm']['phone'] ;
            $model->status = $post_data['RegisterForm']['status'];
            $model->role = $post_data['RegisterForm']['role'];
            $model->avatar  = UploadedFile::getInstance($model, 'avatar');


            if(isset($post_data['RegisterForm']['password'])){
                $password = $post_data['RegisterForm']['password'];
                if (!empty($password)){
                    $model->password = $password;
                }
            }
            if(!$model->validate()){
                return $this->returnAjax(400, current($model->getFirstErrors()), Url::toRoute("/system/admin-user"));
            }
            $add_rs = $model->editUser($use_id) ;
            if(!$add_rs['status']){
                return $this->returnAjax(400, $add_rs['msg'], Url::toRoute("/system/admin-user"));
            }
            array_unshift($getdata, '/system/admin-user');
            return $this->returnAjax(200, $add_rs['msg'], Url::toRoute($getdata));
        }

        $model->setAttributes($user->getAttributes());
        $model->password = "" ;
        return $this->renderPartial('edit_user',["model"=>$model]);
    }

    /**
     * 删除用户
     */
    public function actionDelUser(){
        $user_id_post = Yii::$app->request->post("user_id");

        $getdata = Yii::$app->request->get();

        if(empty($user_id_post)){
            return $this->returnAjax(400, "请不要乱操作", Url::toRoute("/system/admin-user"));
        }

        $user = AdminUser::findOne(["user_id"=>$user_id_post]);

        if(empty($user)){
            return $this->returnAjax(400, "无此工号或已删除，请不要重复操作", Url::toRoute("/system/admin-user"));
        }

        if ($user->username == 'admin') {
            return $this->returnAjax(400, "不能删除超级管理员", Url::toRoute("/system/admin-user"));
        }

        if($user_id_post==1){
            return $this->returnAjax(400, "不允许删除超级管理员", Url::toRoute("/system/admin-user"));
        }

        $del_rs = AdminUser::deleteAdminUser($user_id_post) ;

        array_unshift($getdata, '/system/admin-user');
        return $this->returnAjax(200, $del_rs['msg'], Url::toRoute($getdata));
    }

    /**
     * 评价列表
     * @return string
     */
    public function actionEvalu(){
        $limit = 20 ;
        $searchData = Yii::$app->request->get() ;

        $orderBy = "status asc,id desc" ;
        $arr = EvaluService::findEvaluList($limit,$searchData,$orderBy) ;
        return $this->render('evalu', ['arr' => $arr,"limit"=>$limit]);
    }

    /**
     *  添加评价
     */
    public function actionAddEvalu(){
        $model = new EvaluForm();
        if(!Yii::$app->request->isPost) {
            return $this->renderPartial('add_evalu', ['model'=>$model]);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()){
            $result = $model->add();
            if ($result['code']==200) {
                return $this->returnAjax(200, $result['msg'], Url::toRoute("/system/evalu"));
            } else {
                return $this->returnAjax(400, $result['msg'], Url::toRoute("/system/evalu"));
            }
        }
        return $this->returnAjax(400, current($model->getFirstErrors()), Url::toRoute("/system/evalu"));
    }

    /**
     *  编辑评价
     */
    public function actionEditEvalu(){
        $model = new EvaluForm();

        $id = Yii::$app->request->get("id");
        $data = Evalu::find()->where("id=:id",[":id"=>$id])->one();
        if(empty($data)){
            return $this->redirect(["/tip/index","msg"=>"无此参数","url"=>Url::toRoute("/system/evalu")]) ;
        }

        if(!Yii::$app->request->isPost) {
            $model->title = $data['title'] ;
            $content = $data['content'] ;
            $contentArr = explode("|",$content) ;

            $num = 1 ;
            foreach($contentArr as $val){
                $attr = "desc".$num ;
                $model->$attr = $val ;
                $num = $num + 1;
            }

            return $this->renderPartial('edit_evalu', ['model'=>$model]);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()){
            $result = $model->edit($id);
            if ($result['code']==200) {
                return $this->returnAjax(200, $result['msg'], Url::toRoute("/system/evalu"));
            } else {
                return $this->returnAjax(400, $result['msg'], Url::toRoute("/system/evalu"));
            }
        }
        return $this->returnAjax(400, current($model->getFirstErrors()), Url::toRoute("/system/evalu"));
    }

    /**
     * 删除评价
     */
    public function actionDelEvalu(){
        $id = Yii::$app->request->get("id");

        if(empty($id)){
            return $this->returnAjax(400,'缺少参数') ;
        }

        $evalu = Evalu::find()->where(['id'=>$id])->one();

        if(empty($evalu)){
            return $this->returnAjax(400,'没有该数据') ;
        }

        $rs = $evalu->delete();

        if($rs){
            return $this->returnAjax(200,'删除成功', Url::toRoute("/system/evalu")) ;
        }else{
            return $this->returnAjax(400,'删除失败') ;
        }
    }

    /**
     * 系统参数列表
     * @author hetu
     */
    public function actionContralSet(){
        $query = ContralSet::find();
        $page = new Pagination(['totalCount' =>$query->count(), 'defaultPageSize' => 20]);
        $data = $query->orderBy(["id"=>SORT_DESC])->offset($page->offset)->limit($page->limit)->asArray()->all();
        return $this->render('contral_set',["data"=>$data,"page"=>$page]);
    }

    /**
     *  添加系统参数
     * @author hetu
     */
    public function actionAddContral(){
        $model = new ContralSetForm();
        $model->setScenario("add");
        if(!Yii::$app->request->isPost) {
            return $this->renderPartial('add_contral', ['model'=>$model]);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()){
            $result = $model->add();
            if ($result['status']) {
                $data = ContralSet::find()->where(['status' => 1])->asArray()->all();
                $data = ArrayHelper::index($data, 'unique_mark');
                try {
                    Yii::$app->cache->set('system_param', $data);
                } catch(\Exception $e){
                    $errData = ["msg"=>"保存到redis失败","exception"=>$e] ;
                    BaseToolService::error($errData,"SystemController_actionAddContral_error") ;
                }
                return $this->returnAjax(200, $result['msg'], Url::toRoute("/system/contral-set"));
            } else {
                return $this->returnAjax(400, $result['msg'], Url::toRoute("/system/contral-set"));
            }
        }
        return $this->returnAjax(400, current($model->getFirstErrors()), Url::toRoute("/system/contral-set"));
    }

    /**
     *  编辑系统参数
     * @author hetu
     */
    public function actionEditContral(){
        $username = Yii::$app->admin->identity->username ;
        if($username=="admin"){
            $url = Url::toRoute(["/system/contral-set"]);
        }else{
            $url = Url::toRoute(["/system/param"]);
        }

        $model = new ContralSetForm();
        $id = Yii::$app->request->get("id");
        $data = ContralSet::find()->where("id=:id",[":id"=>$id])->one();
        if(empty($data)){
            return $this->redirect(["tip/index","msg"=>"无此参数","url"=>$url]) ;
        }
        $post_data = Yii::$app->request->post() ;

        if(!Yii::$app->request->isPost) {
            $model->setAttributes($data->getAttributes());

            return $this->renderPartial('edit_contral', ['model'=>$model]);
        }

        if ($model->load($post_data) && $model->validate()){
            $result = $model->edit($id);
            if ($result['status']) {
                $data = ContralSet::find()->where(['status' => 1])->asArray()->all();
                $data = ArrayHelper::index($data, 'unique_mark');
                try {
                    Yii::$app->cache->set('system_param', $data);
                } catch(\Exception $e){
                    $errData = ["msg"=>"保存到redis失败","exception"=>$e] ;
                    BaseToolService::error($errData,"SystemController_actionEditContral_error") ;
                }
                return $this->returnAjax(200, $result['msg'], $url);
            } else {
                return $this->returnAjax(400, $result['msg'], $url);
            }
        }

        return $this->returnAjax(400, current($model->getFirstErrors()), $url);

    }

    /**
     * 删除系统参数
     * @author hetu
     */
    public function actionDelContral(){
        $id_post = Yii::$app->request->post("id");

        if(empty($id_post)){
            return $this->returnAjax(400,'缺少参数',Url::toRoute(["/system/contral-set"])) ;
        }

        $model = ContralSet::find()->where(['id'=>$id_post])->one();

        if(empty($model)){
            return $this->returnAjax(400,'没有该数据',Url::toRoute(["/system/contral-set"])) ;
        }

        $delete = $model->delete();

        if($delete){
            $data = ContralSet::find()->where(['status' => 1])->asArray()->all();
            $data = ArrayHelper::index($data, 'unique_mark');
            try {
                Yii::$app->cache->set('system_param', $data);
            } catch(\Exception $e){
                $errData = ["msg"=>"保存到redis失败","exception"=>$e] ;
                BaseToolService::error($errData,"SystemController_actionDelContral_error") ;
            }
            return $this->returnAjax(200,'删除成功',Url::toRoute(["/system/contral-set"])) ;
        }else{
            return $this->returnAjax(400,'删除失败',Url::toRoute(["/system/contral-set"])) ;
        }
    }


    /**
     * 系统参数列表
     * @author hetu
     */
    public function actionParam(){
        $query = ContralSet::find();
        $page = new Pagination(['totalCount' =>$query->count(), 'defaultPageSize' => 20]);
        $idArr = [56,57,58,59,60,61];
        $data = $query->where(["id"=>$idArr])->orderBy(["id"=>SORT_DESC])->offset($page->offset)->limit($page->limit)->asArray()->all();
        return $this->render('param',["data"=>$data,"page"=>$page]);
    }

}